from . import serializer
import random

__all__ = ['Packet']


_id = random.randint(0, 100)


def get_id():
    # TODO: add code to generate packet ID.
    global _id
    _id += 1
    return _id


class Packet:
    def __init__(self, bytes_data=None, serializer_name=None, **kwargs):
        self._raw_data = bytes_data
        self._data = {}
        self.serializer = serializer_name
        if self._raw_data:
            self.serializer, obj = serializer.deserialize(self._raw_data,
                                                          name=self.serializer)
            for key in obj:
                self[key] = obj[key]

        if "id" not in self:
            self["id"] = get_id()
        for key in kwargs.keys():
            self[key] = kwargs[key]

    def __setitem__(self, key, value):
        self._data[key] = value

    def __getitem__(self, item):
        return self._data[item]

    def __delitem__(self, key):
        if key in self._data:
            del self._data[key]

    def __len__(self):
        return len(self.raw_data)

    def __contains__(self, item):
        return item in self._data

    def __iter__(self):
        return self._data.__iter__()

    def keys(self):
        return self._data.keys()

    def values(self):
        return self._data.values()

    @property
    def raw_data(self):
        return self._raw_data

    @property
    def id(self):
        return self["id"]

    @id.setter
    def id(self, id):
        self["id"] = id

    def __bytes__(self):
        return self.to_bytes(self.serializer)

    def to_bytes(self, serializer_name=None):
        if serializer_name:
            return serializer.serialize(self, serializer_name)
        else:
            return serializer.serialize(self)
